let ctx, subsystems;

let timeoutIDs=[];

function createHandler(eName){
    return async() => {
        await subsystems.events.trigger(eName);
        subsystems.events.unlisten(eName);
    }
}

export default {
    listen(eventDef, name){
        timeoutIDs[name] = setTimeout(createHandler(name), eventDef.timeout);
        return {timeout : new Date().getTime() + eventDef.timeout};
    },
    unlisten(eventObj){
        clearTimeout(timeoutIDs[eventObj.name]);
        delete timeoutIDs[eventObj.name]
    },
    async init(_ctx, _subsystems){
        ctx=_ctx; subsystems=_subsystems;
        let timeouts = await subsystems.db.Events.getAll({type: "timeout"});
        for (let eventObj of timeouts) {
            let timeDiff = eventObj.opts.timeout - new Date().getTime();
            console.log(`timeout ${eventObj.name}, timeDiff:${timeDiff}`);
            if (timeDiff < 0)
                timeDiff = 0;
            timeoutIDs[eventObj.name] = setTimeout(createHandler(eventObj.name), timeDiff);
        }
    }
}